package com.c2b.algorithm.leetcode.base.backtracking;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

/**
 * <a href='https://leetcode.cn/problems/permutations/description/'>全排列(Permutations)</a>
 * <p>给定一个不含重复数字的数组 nums ，返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。</p>
 * <p>你可以按 任何顺序 返回答案。</p>
 * <p>
 * <b>示例：</b>
 * <pre>
 * 示例 1：
 *      输入：nums = [1,2,3]
 *      输出：[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
 *
 * 示例 2：
 *      输入：nums = [0,1]
 *      输出：[[0,1],[1,0]]
 * 示例 3：
 *
 *      输入：nums = [1]
 *      输出：[[1]]
 * </pre>
 * </p>
 *
 * <p>
 * <b>提示：</b>
 *     <ul>
 *         <li>1 <= nums.length <= 6</li>
 *         <li>-10 <= nums[i] <= 10</li>
 *         <li>nums 中的所有整数 互不相同</li>
 *     </ul>
 * </p>
 *
 * @author c2b
 * @since 2023/10/26 16:37
 */
public class LC0046Permutations_M {

    static class Solution {
        public List<List<Integer>> permute(int[] nums) {
            List<List<Integer>> retList = new ArrayList<>();
            if (nums.length == 0) {
                return retList;
            }
            dfs(nums, nums.length, new boolean[nums.length], new ArrayDeque<>(), retList);
            return retList;
        }

        /**
         * 回溯
         *
         * @param remainCount 剩余的数量
         * @param used        记录哪些数字已经被使用过
         * @param path        当前的路径
         * @param retList     结果集
         */
        private void dfs(int[] nums, int remainCount, boolean[] used, Deque<Integer> path, List<List<Integer>> retList) {
            if (remainCount == 0) {
                retList.add(new ArrayList<>(path));
            }
            for (int i = 0; i < nums.length; i++) {
                if (!used[i]) {
                    used[i] = true;
                    path.add(nums[i]);
                    dfs(nums, remainCount - 1, used, path, retList);
                    used[i] = false;
                    path.removeLast();
                }
            }
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        for (List<Integer> list : solution.permute(new int[]{1, 2, 3})) {
            for (Integer integer : list) {
                System.out.print(integer + "  ");
            }
            System.out.println();

        }
        System.out.println("===============");
        for (List<Integer> list : solution.permute(new int[]{1, 2})) {
            for (Integer integer : list) {
                System.out.print(integer + "  ");
            }
            System.out.println();

        }
        System.out.println("===============");
        for (List<Integer> list : solution.permute(new int[]{1})) {
            for (Integer integer : list) {
                System.out.print(integer + "  ");
            }
            System.out.println();

        }
    }
}
